﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Interop;

namespace WPFHostsWin32
{
    public class ControlHost : HwndHost
    {
        IntPtr hwndControl;
        IntPtr hwndHost;
        int hostHeight;
        int hostWidth;

        public ControlHost(double height, double width)
        {
            hostHeight = (int)height;
            hostWidth = (int)width;
        }

        protected override HandleRef BuildWindowCore(HandleRef hwndParent)
        {
            hwndControl = IntPtr.Zero;
            hwndHost = IntPtr.Zero;

            hwndHost = NativeMethods.CreateWindowEx(0, "static", string.Empty,
                                      NativeMethods.WS_CHILD | NativeMethods.WS_VISIBLE,
                                      0, 0,
                                      hostWidth, hostHeight,
                                      hwndParent.Handle,
                                      (IntPtr)NativeMethods.HOST_ID,
                                      IntPtr.Zero,
                                      0);

            hwndControl = NativeMethods.CreateWindowEx(0, "listbox", string.Empty,
                                          NativeMethods.WS_CHILD | NativeMethods.WS_VISIBLE | NativeMethods.LBS_NOTIFY
                                            | NativeMethods.WS_VSCROLL | NativeMethods.WS_BORDER,
                                          0, 0,
                                          hostWidth, hostHeight,
                                          hwndHost,
                                          (IntPtr)NativeMethods.LISTBOX_ID,
                                          IntPtr.Zero,
                                          0);

            return new HandleRef(this, hwndHost);
        }

        protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            handled = false;
            return IntPtr.Zero;
        }

        protected override void DestroyWindowCore(HandleRef hwnd)
        {
            NativeMethods.DestroyWindow(hwnd.Handle);
        }

        public IntPtr Hwnd
        {
            get { return hwndControl; }
        }
    }
}